package com.game.modular.gameCore.map.service.impl;

import com.game.modular.gameCore.map.service.CoreMapService;
import lombok.extern.slf4j.Slf4j;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.game.modular.gameCore.map.mapper.CoreMapMapper;
import com.game.modular.gameCore.map.domain.CoreMap;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.annotation.PostConstruct;


/**
 * 战斗地图(CoreMap)表服务实现类
 *
 * @author cxy
 * @since 2024-07-30 20:47:06
 */
@Slf4j
@Service
public class CoreMapServiceImpl extends ServiceImpl<CoreMapMapper, CoreMap> implements CoreMapService {
    Cache<String, Map<Integer,CoreMap>> cache = Caffeine.newBuilder().build();
    
    @PostConstruct
    private void init() {
        CoreMap initSelect = CoreMap.builder().build();
        List<CoreMap> list = this.list(new LambdaQueryWrapper<>(initSelect));
        log.info("开始缓存战斗地图数据,数据量为:{}",list.size());
        cache.put(
                "coreMap", 
                list.stream().collect(Collectors.toMap(CoreMap::getId, CoreMap -> CoreMap))
        );
        log.info("战斗地图数据缓存完成");
    }

    public List<CoreMap> listCache() {
        Map<Integer,CoreMap> values = cache.getIfPresent("coreMap");
        if (Objects.isNull(values)) {
            throw new RuntimeException("战斗地图数据为空");
        }
        return new ArrayList<>(values.values());
    }   
    
    public CoreMap getCache(Integer id) {
        return listCache().get(id);
    }
}
